#include "HelloWorldScene.h"
#include "View/PanelScore.h"
#include "cocos-ext.h"
#include "spine/Json.h"
#include "Component/CollisionTree.h"

using namespace cocos2d::gui;
USING_NS_CC;
USING_NS_CC_EXT;

CCScene* HelloWorld::scene()
{
    // 'scene' is an autorelease object
    CCScene *scene = CCScene::create();
    
    // 'layer' is an autorelease object
    HelloWorld *layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !CCLayer::init() )
    {
        return false;
    }
    
	// check swipe - loicuoi
	isTouchDown = false;
	// end check swipe

	mMonkeyHeath = 100;

	setTouchEnabled( true );

	mSize = CCDirector::sharedDirector()->getWinSize();

    CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
    CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();

	CCSprite* backGround = CCSprite::create("skype_1024.png");
	backGround->setPosition(ccp(visibleSize.width/2, visibleSize.height/2));

	addChild(backGround, -1);
	
	// Tao moi 1 doi tuong Cloud
	fAddCloud();

	//add monkey
	fAddMonkey();

	//add Vines
	fAddVines();

	// Add tree
	fAddTree();

	// Monkey heath UI
	ul = UILayer::create();
	fAddMonkeyHeathUI();


	scheduleUpdate();   
	return true;
}
void HelloWorld::menuHttpRequestCallback(CCObject* pSender)
{
	//fGetData();
	fPostData();
}

// Click to get data by method GET
void HelloWorld::fGetData()
{
	CCHttpClient* httpClient = CCHttpClient::getInstance();

	CCHttpRequest* httpReq =new CCHttpRequest();

	httpReq->setRequestType(CCHttpRequest::kHttpGet);
	httpReq->setUrl("http://softtech.vn/monkeyslide/index.php");
	httpReq->setResponseCallback(this,callfuncND_selector(HelloWorld::onHttpRequestCompleted));
	httpReq->setTag("FirstNet");
	httpClient->setTimeoutForConnect(30);
	httpClient->send(httpReq);

	httpReq->release();
}

// Click to POST data by method POST
void HelloWorld::fPostData()
{
	 // Setting HTTP Request Header
	std::vector<std::string> headers;
	headers.push_back("Content-Type: application/json; charset=utf-8");
	// Creating a URL
	cocos2d::extension::CCHttpRequest * request = new cocos2d::extension::CCHttpRequest();
	request->setUrl("http://softtech.vn/monkeyslide/index.php");
 
	const char* postData = "visitor=hello";
	unsigned int postDataLen = strlen(postData);

	// If you want to use GET method, replace kHttpPost to kHttpGet
	request->setRequestType(cocos2d::extension::CCHttpRequest::kHttpPost);
	request->setResponseCallback(this, callfuncND_selector(HelloWorld::onHttpRequestCompleted));
	request->setRequestData(postData, postDataLen);
	//request->setHeaders(headers);
	request->setTag("POST Request");
 
	// Execute
	cocos2d::extension::CCHttpClient::getInstance()->send(request);
 
	// Release the Connection
	request->release();
}

// Get response data with String data
void HelloWorld::onHttpRequestCompleted(cocos2d::CCNode *sender, void *data)
{
	cocos2d::extension::CCHttpResponse * response = (cocos2d::extension::CCHttpResponse *)data;
	if (!response)
	{
	return;
	}
	if (0 != strlen(response->getHttpRequest()->getTag()))
	{
	CCLog("%s completed", response->getHttpRequest()->getTag());
	}
 
	// Check the HTTP Status Code
	int statusCode = response->getResponseCode();
	char statusString[64] = {};
	sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag());
	CCLog("response code: %d", statusCode);
 
	// A connection failure
	if (!response->isSucceed())
	{
	CCLog("response failed");
	CCLog("error buffer: %s", response->getErrorBuffer());
	return;
	}
 
	// The data will be placed in the buffer.
	std::vector<char> * buffer = response->getResponseData();
	char * concatenated = (char *) malloc(buffer->size() + 1);
	std::string s2(buffer->begin(), buffer->end());
	strcpy(concatenated, s2.c_str());
 
	 //JSON Parser. Include "spine/Json.h". Get it from Server and Parse some value you want
	Json * json = Json_create(concatenated);
	const char * test1 = Json_getString(json, "test1", "default");
	const char * test2 = Json_getString(json, "test2", "default");
 
	// View the console
	CCLog("HTTP Response : key 1 : %s", test1);
	CCLog("HTTP Response : key 2 : %s", test2);
 
	// Delete the JSON object
	Json_dispose(json);

	CCLog(concatenated);
}


void HelloWorld::fAddMonkeyHeathUI()
{
	ul->addWidget(GUIReader::shareReader()->widgetFromJsonFile("UI/MonkeyHeath/MonkeyHeath_1.json"));
	ul->setPosition(ccp(0,mSize.height - 200));
	addChild(ul); 
}
void HelloWorld::fUpdateHeath(int mHeath)
{
	mMonkeyHeath = mHeath;

	if(ul != NULL)
	{
		UILoadingBar* loadingBar = dynamic_cast<UILoadingBar*>(ul->getWidgetByName("ProgressBar_2"));
		loadingBar->setPercent(mMonkeyHeath);
	}
}

void HelloWorld::fAddCloud()
{
	Cloud *nCloud = new Cloud();
	this->addChild(nCloud,2);
	nCloud->setPosition(ccp(mSize.width/2,mSize.height/2));
	mCloud = nCloud;

	// Test di chuyen sang trai -> OK
	//nCloud->fMoveLeft();
}

void HelloWorld::fAddTree()
{
	mTree = mTree1 = NULL;

	Tree * nTree = new Tree(mMonkey,mCloud);
	nTree->setPosition(ccp( mSize.width/2, nTree->fGetSprite()->getContentSize().height/2));	
	//nTree->addComponent(new MonkeyCollision(mMonkey));
	this->addChild(nTree,2);
	mTree = nTree;

	
	mMonkey->fChangeDirection();
	
	float nWidthTree = mTree->fGetSprite()->getContentSize().width;
	mMonkey->fRunChangeDirection(nWidthTree/2);
}

void HelloWorld::fAddTree(CCPoint p)
{
	Tree * nTree = new Tree(mMonkey,mCloud);
	this->addChild(nTree,2);
	nTree->setPosition(ccp(p.x* mSize.width,mSize.height + nTree->fGetSprite()->getContentSize().height/2));
	nTree->addComponent(new CollisionTree(mMonkey,mCloud));
	if(mTree1 == NULL || !mTree1->fGetIsChoose())
	{
		mTree1 = nTree;
		mTree->fSetIsChoose(false);
	}
	else
	{
		mTree = nTree;
		mTree1->fSetIsChoose(false);
	}
}

void HelloWorld::fAddMonkey()
{
	mVines = NULL;
	Monkey* nMonkey = Monkey::create();
	nMonkey->setPosition(ccp( mSize.width/2,mSize.height/3));

	/*float anchorW = nMonkey->fGetArmature()->boundingBox().size.width/2;
	float anchorH = nMonkey->fGetArmature()->boundingBox().size.height/2;
	nMonkey->setAnchorPoint(ccp(anchorW,anchorH));*/

	nMonkey->setZOrder(2);
	nMonkey->fSetStatus(Idle);
	mMonkey = nMonkey;
	this->addChild(mMonkey, kZoderMonkey);
	mMonkey->fGetArmature()->getAnimation()->setMovementEventCallFunc(this, movementEvent_selector(HelloWorld::animationEvent));
}

void HelloWorld::fAddVines()
{
	Vines* nVines = new Vines(mMonkey);
	nVines->setPosition(ccp(mSize.width *3/4 , mSize.height));
	mVines = nVines;
	addChild(mVines,10);
}

void HelloWorld::fSetScore(int score)
{
	mScore = score;
}
int HelloWorld::fGetScore()
{
	return mScore;
}

// Background scroll here
void  HelloWorld::update(float delta)
{

	

}

void HelloWorld::animationEvent(CCArmature *pArmature, MovementEventType movementType, const char *movementID)
{
	if(movementType == COMPLETE)
	{
		// action of Hero
		if(strcmp(movementID,"nhaybamcay") == 0) //loading
		{
			mMonkey->fSetStatus(isDie);
		}
	}
}
//---------------------------------------------->

void HelloWorld::onEnter() {
    CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
    CCLayer::onEnter();
}

void HelloWorld::onExit() {
    CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
    CCLayer::onExit();
}

bool HelloWorld::ccTouchBegan(CCTouch* touch, CCEvent* event)
{

	// Check swipe - loicuoi
	initialTouchPos[0] = touch->getLocation().x;
    initialTouchPos[1] = touch->getLocation().y;
    currentTouchPos[0] = touch->getLocation().x;
    currentTouchPos[1] = touch->getLocation().y;
    isTouchDown = true;
	// end check swipe

	return true;
}

void HelloWorld::ccTouchEnded(CCTouch* touch, CCEvent* event)
{
	
	// End check swipe	

	if (true == isTouchDown)
    {
		// Check swipe and move to
		// do something when swipe is detected
        if (initialTouchPos[0] - currentTouchPos[0] > visibleSize.width * 0.05)
        {
            CCLOG("SWIPED LEFT");

			//if(mMonkey->fGetDirection() == isTurningRight)
			//{
			//	mMonkey->fSetDirection(isTurningLeft);
			//	// isJumpLeft
			//	
			//}
			//mMonkey->fSetStatus(isJumpLeft);

			if(mTree != NULL)
			{
				mTree->runAction(CCMoveBy::create(0.7,ccp(mSize.width/2,0)));
			}
			if(mTree1 != NULL)
			{
				mTree1->runAction(CCMoveBy::create(0.7,ccp(mSize.width/2,0)));
			}
			
			mMonkey->fSetDirection(1);
			mMonkey->fSetStatus(isJump);
        }
        else if (initialTouchPos[0] - currentTouchPos[0] < - visibleSize.width * 0.05)
        {
			CCLOG("SWIPED RIGHT");
			if(mTree != NULL)
			{
				mTree->runAction(CCMoveBy::create(0.7,ccp(-mSize.width/2,0)));
			}
			if(mTree1 != NULL)
			{
				mTree1->runAction(CCMoveBy::create(0.7,ccp(-mSize.width/2,0)));
			}
			
			mMonkey->fSetDirection(-1);
			mMonkey->fSetStatus(isJump);

			//
			//if(mMonkey->fGetDirection() == isTurningLeft)
			//{
			//	mMonkey->fSetDirection(isTurningRight);
			//	// isJumpRight
	
			//}
			//mMonkey->fSetStatus(isJumpRight);
			//if(mVines != NULL)
			//{
			//	mVines->fCheckStart();
			//}

        }
        else if (initialTouchPos[1] - currentTouchPos[1] > visibleSize.width * 0.05)
        {
           // CCLOG("SWIPED DOWN");
        }
        else if (initialTouchPos[1] - currentTouchPos[1] < - visibleSize.width * 0.05)
        {
            //CCLOG("SWIPED UP");
        }
		else //TOUCH
		{
			int nDirection = mMonkey->fGetDirection();
			mMonkey->fSetDirection(-nDirection);
			float nWidthTree = mTree->fGetSprite()->getContentSize().width;
			
			mMonkey->fRunChangeDirection(nWidthTree/2);
		}
	
	// check swipe - loicuoi
	isTouchDown = false;

	}
}

void HelloWorld::ccTouchMoved(CCTouch* touch, CCEvent* event)
{
	// Check swipe - loicuoi
	currentTouchPos[0] = touch->getLocation().x;
    currentTouchPos[1] = touch->getLocation().y;
	// End check swipe

}

void HelloWorld::menuCloseCallback(CCObject* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
	CCMessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
#else
    CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
#endif
}

void HelloWorld::draw()
{
	CCRect c2 = mMonkey->fGetArmature()->getBone("Layer6")->getDisplayRenderNode()->boundingBox();
	float x1,y1,x2,y2, tam;

	float  a= mMonkey->fGetArmature()->getScaleX();

	x1 = c2.getMinX()*a+mMonkey->getPositionX();
	y1 = c2.getMinY()+mMonkey->getPositionY();
	x2 = c2.getMaxX()*a+mMonkey->getPositionX();
	y2 = c2.getMaxY()+mMonkey->getPositionY();
	ccDrawRect(ccp(x1,y1),ccp(x2,y2));


	CCRect c1 = mTree->fGetSprite()->boundingBox();

	x1 = c1.getMinX() + mTree->getPositionX();
	y1 = c1.getMinY() + mTree->getPositionY();
	x2 = x1 + c1.size.width;
	y2 = y1 + c1.size.height;

	ccDrawRect(ccp(x1,y1),ccp(x2,y2));


}